import json

from django.contrib.auth import logout
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from apps.areas.models import Area
# 使用Django缓存进行省市区数据获取
from django.core.cache import cache
import re
# 导入地址表进行保存
from apps.user1.models import Address


# Create your views here.
class AreasView(View):
    def get(self,request):
        # 判断缓存中是否已经存储过省的数据，如果存储过，直接返回存储数据
        province_list = cache.get('province_list')
        if province_list:
            return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})
        else:
            # 查询所有省信息
            data = Area.objects.filter(parent_id = None)
            # 将省数据存储到列表中进行返回
            province_list = []
            for s in data:
                province_list.append({
                    'id':s.id,
                    'name':s.name
                })
            # 将数据存入redis缓存
            cache.set('province_list',province_list,3600)
            # 返回结果
            return JsonResponse({'code':0,'errmsg':'ok','province_list':province_list})


# 获取市的信息
# 获取区县信息
class SubAreasView(View):

    # pk是前端传递的省的id值市的信息
    def get(self,request,pk):
        # 1、根据pk查询省的信息或市的信息
        # 判断缓存中是否已经存储过省的数据，如果存储过，直接返回存储数据
        sub_data = cache.get('sub_data_%s' % pk)
        if sub_data:
            return JsonResponse({
                'code':0,
                'errmsg':'ok',
                'sub_data':sub_data
            })
        else:
            # 1、根据pk查询省的信息或市的信息
            s = Area.objects.get(id = pk)
            # 2、根据pk查询省对应的市的信息或市对应的区县信息subs
            citys = Area.objects.filter(parent_id = pk)
            # 3、构造相应数据进行返回
            subs = []
            for city in citys:
                subs.append({
                    'id': city.id,
                    'name': city.name
                })
            sub_data = {
                'id': s.id,
                'name': s.name,
                'subs': subs
            }
            # 写入缓存
            cache.set('sub_data_%d' % pk, sub_data, 3600)
            return JsonResponse({
                'code':0,
                'errmsg':'ok',
                'sub_data':sub_data
                })


# 保存地址
class CreateAddressView(View):
    def post(self,request):
        # 1、获取前端的数据，json数据
        json_data = request.body.decode()
        # 2、转化json数据为字典
        dict_data = json.loads(json_data)
        # 3、提取对应的字段数据
        receiver = dict_data.get('receiver')
        province_id = dict_data.get('province_id')
        city_id = dict_data.get('city_id')
        district_id = dict_data.get('district_id')
        place = dict_data.get('place')
        mobile = dict_data.get('mobile')
        tel = dict_data.get('tel')
        email = dict_data.get('email')
        # 4、验证数据
        # 4-1、验证数据完整性
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '参数不完整'}, status=400)
            # 4-2、验证手机号
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式不正确'}, status=400)
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '参数email有误'})
            # 5、保存数据 ?怎么获取用户？
            # 在地址页面用户是登录的，可以使用reques.user获取用户信息
        address = Address.objects.create(user=request.user, receiver=receiver, title=receiver, province_id=province_id,
                               city_id=city_id,
                               district_id=district_id,
                               place=place,
                               mobile=mobile,
                               tel=tel,
                               email=email)
        # 增加默认地址判断，如果在保存地址时，没有默认地址，就将保存的地址作为默认地址
        default_address = request.user.default_address
        if default_address is None:
            request.user.default_address = address
            # 更新赋值后要保存
            request.user.save()
        # 6、返回结果
        return JsonResponse({'code': 0, 'errmsg': "ok"})


# 获取地址
class UserAddressView(View):
    def get(self,request):
        # 1、获取用户
        user = request.user
        # 2、根据用户查询对应的地址信息
        addresses = Address.objects.filter(user = user,is_deleted= False)
        addresses_list = []
        for address in addresses:
            addresses_list.append( {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        # 3、获取用户的默认地址
        default_address_id = user.default_address.id
        # 返回结果
        return JsonResponse({'code': 0, 'errmsg': "ok",'default_address_id':default_address_id,'addresses':addresses_list})


# 设置默认地址
class UserDefaultAddressView(View):
    def put(self,request,pk):
        # 1、获取用户
        user= request.user
        # 2、获取用户地址
        address = Address.objects.get(user = user,id = pk)
        # 3、设置默认地址
        user.default_address = address
        # 更新赋值后要保存
        user.save()
        # 4、返回结果
        return JsonResponse({'code': 0, 'errmsg': "ok"})


# 修改密码
class ChangePasswordView(View):
    def put(self,request):
        # 1、获取数据，json形式
        json_data = request.body.decode()
        dict_data = json.loads(json_data)
        old_password = dict_data.get('old_password')
        new_password = dict_data.get('new_password')
        new_password2 = dict_data.get('new_password2')
        # 2、获取用户
        user = request.user
        # 3、校验数据
        # 验证数据完整性
        if not all([old_password,new_password,new_password2]):
            return JsonResponse({'code': 400, 'errmsg': '数据不完整'}, status=400)
        # 密码校验，原始密码是否正确 check_password方法成功返回true
        if not user.check_password(old_password):
            return JsonResponse({'code': 400, 'errmsg': '密码不正确'}, status=400)
        # 判断密码格式
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式不正确'}, status=400)
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', new_password2):
            return JsonResponse({'code': 400, 'errmsg': '密码格式不正确'}, status=400)
        # 判断两次是否一致
        if new_password != new_password2:
            return JsonResponse({'code': 400, 'errmsg': '密码不一致'}, status=400)
        # 4、修改密码 set_password
        user.set_password(new_password)
        user.save()
        # 退出状态保持，将原有用户删除，实现的是退出登录操作
        logout(request)
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.delete_cookie('username')
        # 5、返回结果
        return response


class ChangeAddressView(View):
    # 修改地址
    def put(self,request,pk):
        # 获取数据，json形式
        json_data = request.body.decode()
        dict_data = json.loads(json_data)
        receiver = dict_data.get('receiver')
        province_id = dict_data.get('province_id')
        city_id = dict_data.get('city_id')
        district_id = dict_data.get('district_id')
        place = dict_data.get('place')
        mobile = dict_data.get('mobile')
        tel = dict_data.get('tel')
        email = dict_data.get('email')
        # 获取用户
        user = request.user
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})


        # 修改地址
        Address.objects.filter(user = user,id=pk).update(
            title= receiver,
            receiver= receiver,
            province= province_id,
            city= city_id,
            district= district_id,
            place= place,
            mobile= mobile,
            tel= tel,
            email= email
        )

        # 返回结果
        # 获取用户地址
        address = Address.objects.get(user = user,id=pk)
        new_address ={
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({
            'code': 0,
            'errmsg': '更新地址成功',
            'address': new_address})

    # 删除地址
    def delete(self,request,pk):
        # 获取用户
        user = request.user
        # 获取地址
        address = Address.objects.get(user = user, id = pk)
        # 删除地址
        address.is_deleted = True
        address.save()
        # 返回结果
        return JsonResponse({'code': 0,'errmsg': 'ok'})


# 修改地址标题
class ChangeAddressTitleView(View):
    def put(self,request,pk):
        # 获取用户
        user = request.user
        # 获取前端数据
        json_data = request.body.decode()
        # 前端数据字典化
        dict_data = json.loads(json_data)
        # 获取地址标题数据
        title = dict_data.get('title')
        # 获取地址
        address = Address.objects.get(user = user, id = pk)
        # 修改地址
        address.title = title
        address.save()
        # 返回地址
        return JsonResponse({'code': 0,'errmsg': 'ok'})
